//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace OpenLS.Spreadsheet.Expressions
{
    sealed class SharedExpressionReference : Expression
    {
        public SharedExpressionReference(SharedExpression exp, Cell target)
        {
            Contract.Requires(exp != null);
            _sharedExpression = exp;
            _target = target;
        }
        public override IEnumerable<Expression> GetSubExpressions()
        {
            Expression exp = ActualExpression;
            return exp.GetSubExpressions();
        }
        public Expression ActualExpression
        {
            get
            {
                Expression result = _sharedExpression.TopLeftExpression.Offset(_target.Address - _sharedExpression.Address.TopLeft);
                return result;
            }
        }
        internal override Expression Transposed(Cell target)
        {
            throw new NotImplementedException();
        }
        protected override object GetValueAsTop(EvaluationContext context)
        {
            EvaluationContext newContext = context.CreateOffseted(GetOffset());
            return _sharedExpression.TopLeftExpression.GetNormalizedValue(newContext);
            //\\            return ActualExpression.GetNormalizedValue(context);
        }
        CellRelativeAddress GetOffset()
        {
            return _target.Address - _sharedExpression.Address.TopLeft;
        }
        public SharedExpression SharedExpression { get { return _sharedExpression; } }
        readonly SharedExpression _sharedExpression;
        readonly Cell _target;


        public override string GetText(TextContext context)
        {
            return ActualExpression.GetText(context);
        }

        public override IEnumerable<IDependencyNode> GetPrecedents(EvaluationContext context)
        {
            EvaluationContext newContext = context.CreateOffseted(GetOffset());
            return SharedExpression.TopLeftExpression.GetPrecedents(newContext);
        }

        protected override object GetObjectImp(EvaluationContext context)
        {
            throw new NotImplementedException();
/*
            return ActualExpression.GetObject(context);
*/
        }

        public override Expression Offset(CellRelativeAddress a)
        {
            throw new NotImplementedException();
        }
    }
}
